import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'

// 创建axios实例
const request = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const { data } = response
    
    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
    if (response.status === 200) {
      return data
    }
    
    // 否则的话抛出错误
    return Promise.reject(new Error(data.message || 'Error'))
  },
  error => {
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          ElMessage({
            message: '登录已过期，请重新登录',
            type: 'error',
            duration: 4000,
            showClose: true,
            center: true,
            offset: 80
          })
          localStorage.removeItem('token')
          localStorage.removeItem('userRole')
          router.push('/login')
          break
        case 403:
          ElMessage({
            message: '没有权限访问',
            type: 'error',
            duration: 4000,
            showClose: true,
            center: true,
            offset: 80
          })
          break
        case 404:
          ElMessage({
            message: '请求的资源不存在',
            type: 'error',
            duration: 4000,
            showClose: true,
            center: true,
            offset: 80
          })
          break
        case 400:
          // 400错误（验证失败）不在这里显示，让具体的组件处理
          break
        case 500:
          ElMessage({
            message: '服务器内部错误',
            type: 'error',
            duration: 4000,
            showClose: true,
            center: true,
            offset: 80
          })
          break
        default:
          ElMessage({
            message: data.message || '请求失败',
            type: 'error',
            duration: 4000,
            showClose: true,
            center: true,
            offset: 80
          })
      }
    } else {
      ElMessage({
        message: '网络错误，请检查网络连接',
        type: 'error',
        duration: 4000,
        showClose: true,
        center: true,
        offset: 80
      })
    }
    
    return Promise.reject(error)
  }
)

export default request
